package com.solocredit.finance.ui.splash.act

import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.solocredit.finance.R
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.base.utils.helper.ActivityStackManager
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaSplashBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.main.act.MullaMainAct
import com.solocredit.finance.ui.splash.impl.MullaSplashPresenterImpl
import com.solocredit.finance.ui.splash.view.IMullaSplashView
import com.solocredit.finance.ui.user.act.MullaUserLoginAct
import com.solocredit.finance.utils.dialog.FlexiMolaUpdateDialog
import com.solocredit.finance.utils.dialog.LanguageDialog
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.FlexiMolaUpdateHelper
import com.solocredit.finance.utils.helper.MullaAnalysisHelper
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import com.solocredit.finance.utils.language.LocaleContract
import com.solocredit.finance.utils.language.MultiLanguages
import java.util.Locale
import java.util.TimeZone


/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/24 11:03
 * @Annotation：启动页面
 */
class MullaSplashAct : MvpAct<IMullaSplashView, MullaSplashPresenterImpl>(),IMullaSplashView {
    lateinit var binding: ActMullaSplashBinding
    private var updateHelper: FlexiMolaUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            // TODO: 更新成功，进入主界面
            checkFlexiMolaEnterAction()
        } else {
            // 1、用户取消或失败，不处理，继续进入主界面
            // 2、如果需要强制，建议跳转应用商店，拦截进入主界面
            if (updateHelper == null) {
                checkFlexiMolaEnterAction()
                return@registerForActivityResult
            }
            updateHelper?.callBackNoUpdate {
                checkFlexiMolaEnterAction()
            }
        }
    }

    override fun createPresenter(): MullaSplashPresenterImpl {
        return MullaSplashPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaSplashBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        //关闭所有页面
        ActivityStackManager.finishAllActivity(MullaSplashAct::class.java)
        //启动需要重置审核中、放款中显示的公告提示次数
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_DIALOG_NOTICE_NUM,0)
    }

    override fun initMullaListener() {
    }

    override fun initMullaData() {
        showMullaLoading(isTOuchOut = false, isCancel = true)
        presenter.loadMullaTimeZoneAction()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.visibility = View.VISIBLE
            ImageUtil.instance?.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))
            binding.textLicenseDesc.text = licenseInfo.optString("desc")
            binding.textLicenseValue.text = licenseInfo.optString("companyName")
        }
    }

    /**
     * 显示选择语言
     */
    private fun showMullaLanguageDialog(){
        val languageDialog = LanguageDialog(this,"Launch Page",object : LanguageDialog.IDialogCallback{
            override fun settingLanguageEnglish() {
                saveSelectLanguageAction(LocaleContract.getEnglishLocale())
            }
            override fun settingLanguageSwahili() {
                saveSelectLanguageAction(LocaleContract.getSwahiliLocale())
            }
        })
        languageDialog.setCancelable(false)
        languageDialog.setCanceledOnTouchOutside(false)
        languageDialog.show()
    }
    /**
     * 设置语言
     */
    private fun saveSelectLanguageAction(newLocale: Locale){
        //是否需要重启
        val restart = MultiLanguages.setAppLanguage(this@MullaSplashAct,newLocale)
        if (restart) {
            // 我们可以充分运用 Activity 跳转动画，在跳转的时候设置一个渐变的效果
            onIntent(MullaSplashAct::class.java)
            overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out)
            finish()
        } else {
            showMullaLoading(isTOuchOut = false, isCancel = true)
            presenter.loadMullaCommonConfigAction()
        }
    }

    /**
     * 获取地区转发成功
     */
    override fun showMullaTimeZoneRequestData(dataString: String) {
        var timeZone = ""
        var zoneCode = ""
        var zoneCountry = ""

        dataString.split(",").apply {
            if (this.isNotEmpty()){
                timeZone = this[0].trim()
            }
            if (this.size >= 2){
                zoneCode = this[1].trim()
            }
            if (this.size >= 3){
                zoneCountry = this[2].trim()
            }
        }

        //保存时区id
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_ID, TimeZone.getDefault().id)
        //保存转发地区
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE,timeZone)
        //保存转发地区 区号
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_CODE,zoneCode)
        //保存国家标识
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_COUNTRY,zoneCountry)
        //添加埋点
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LAUNCH_START)

        //初始化analysis lib 赋值 转发地区
        MullaAnalysisHelper.initAnalysisLibAtZoneSuccess()

        //是否是坦桑地区
        if (MullaConfigs.isTanz()){
            if (!SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_LANGUAGE_LAUNCH)){
                hideMullaLoading()
                showMullaLanguageDialog()
            } else {
                presenter.loadMullaCommonConfigAction()
            }
        } else {
            presenter.loadMullaCommonConfigAction()
        }
    }

    /**
     * 客服配置获取成功
     */
    override fun showFlexiMolaConfigSuccess() {
        //是否强制更新版本
        val isMustUpdate = MullaCustomConfigsHelper.isFlexiMolaUpdateMust()
        if (isMustUpdate){
            //强制更新
           showFlexiMolaUpdateDialog()
            return
        }
        checkFlexiMolaEnterAction()
    }

    /**
     * 跳转到首页 || 登录页
     */
    private fun checkFlexiMolaEnterAction(){
        //已登录 - 进入主页
        if (SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_LOGIN)){
            //初始化analysis lib 赋值 用户id 和 token
            MullaAnalysisHelper.initAnalysisLibAtLoginSuccess()
            enterFlexiMolaMainPage()
        } else {//进入登录页
            enterFlexiMolaLoginPage()
        }
    }

    /**
     * 进入登录页
     */
    private fun enterFlexiMolaLoginPage() {
        onIntent(MullaUserLoginAct::class.java)
        finish()
    }

    /**
     * 进入首页
     */
    private fun enterFlexiMolaMainPage() {
        onIntent(MullaMainAct::class.java)
        finish()
    }

    /**
     * 版本更新Dialog
     */
    private fun showFlexiMolaUpdateDialog(){
        val updateDialog = FlexiMolaUpdateDialog(this,"Launch page",object : FlexiMolaUpdateDialog.IDialogCallback{
            override fun onUpdateClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = FlexiMolaUpdateHelper(this@MullaSplashAct, true, updateLauncher)
                    }
                    updateHelper?.onFlexiMolaCheckVersionUpdate { checkFlexiMolaEnterAction() }
                } catch (e: Exception) {
                    checkFlexiMolaEnterAction()
                }
            }
        })
        updateDialog.show()
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.onResumeFlexiMolaInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LAUNCH_END)
    }
}